import { Component } from '@angular/core';
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { File as FileS } from '@ionic-native/file/ngx';
import axios from 'axios';
import { ToastController } from '@ionic/angular';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import { LoadingController } from '@ionic/angular';


@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
  public base64ImgStr: string;
  public baseApi = 'https://crmdata.amj99.com/api/Demo/';
  public authorization = 'Bearer 57B57D1F-1B57-40FE-A8C5-41BA57AE507B';
  public loading: any;
  constructor(
    private camera: Camera,
    private transfer: FileTransfer,
    private fileOpener: FileOpener,
    private file: FileS,
    private toastController: ToastController,
    private androidPermissions: AndroidPermissions,
    private loadingController: LoadingController
  ) {
    this.getPrmissions();
  }
  /**
   * 检查获取手机权限
   * @
   */
  getPrmissions() {
    this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE).then(
      (result) => {
        console.log('本机权限状态:' + result.hasPermission);
      }, (err) => {
        //申请手机权限
        this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE);
      });
    return new Promise((resolve) => {
      this.androidPermissions.requestPermissions(
        [this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE, this.androidPermissions.PERMISSION.GET_ACCOUNTS]).then((res) => {
          resolve(res);
        });
    });
  }
  /**
   * base64转blob
   *
   * @param data
   * @param filename
   * @returns
   */
  dataURLtoBlob(data) {
    const arr = data.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }
  /**
   * blob转换成file
   *
   * @param theBlob
   * @param fileName
   * @returns
   */
  blobToFile(theBlob){
    theBlob.lastModifiedDate = new Date();
    theBlob.name = 'file';
    return theBlob;
  }
  /**
   * 上传图片
   */
  uploadImg() {
    console.log('开始拍摄');
    const options: CameraOptions = {
      quality: 50,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    };
    this.camera.getPicture(options).then((imageData) => {
      const base64Image = 'data:image/png;base64,' + imageData;
      const blob = this.dataURLtoBlob(base64Image);
      const file = this.blobToFile(blob);
      // 组合数据上传
      const formData = new FormData();
      formData.append('file', file);
      this.uploadFileService(formData);
    }, (err) => {
      // Handle error
    });
  }
  /**
   * 上传文件服务
   *
   * @param formData
   */
  uploadFileService(formData){
    this.presentLoading();
    axios({
      headers: {
        Authorization: this.authorization
      },
      method: 'post',
      url: `${this.baseApi}Upload`,
      data: formData
    }).then(res => {
      this.loading.dismiss();
      if (res.status === 200) {
        this.presentToast();
      }
    });
  }
  /**
   * 选择文件上传
   */
  uploadFile(file) {
    const fileObj = file.target.files[0];
    const formData = new FormData();
    formData.append('file', fileObj);
    this.uploadFileService(formData);
  }
  /**
   * 上传提示
   */
  async presentLoading(msg = '上传中，请稍后~') {
    this.loading = await this.loadingController.create({
      cssClass: 'my-custom-class',
      message: msg,
      spinner: 'circles',
      duration: 20000
    });
    await this.loading.present();
  }
  /**
   * 完成提示
   *
   * @param msg 提示语
   */
  async presentToast(msg: string = '文件上传成功~') {
    const toast = await this.toastController.create({
      message: msg,
      position: 'bottom',
      duration: 2000
    });
    toast.present();
  }
  fileClick() {
    document.getElementById('file').click();
  }
  /**
   * 下载文件
   */
  downloadFile(): void {
    const fileTransfer: FileTransferObject = this.transfer.create();
    const saveurl = this.file.externalDataDirectory ? this.file.externalDataDirectory : this.file.dataDirectory;
    const apk = saveurl + 'file/' + `${new Date().getTime()}.xlsx`;
    const fileUrl = 'https://crmdata.amj99.com/Temp/prod.xlsx';
    this.presentLoading('文件下载中,请稍后~');
    fileTransfer.download(encodeURI(fileUrl), apk).then((entry) => { // 下载文件
      this.loading.dismiss();
      this.fileOpener.open(apk, 'application/msexcel') // 打开文件
        .then((e) => {
          console.log('File is opened', e);
        })
        .catch(e => {
          console.log('Error openening file', e);
        });
    }, (error) => {
      alert(JSON.stringify(error));
    });
  }

}
